<template>
  <div class="schedule-management-container">
    <div class="page-header">
      <h2>排期管理</h2>
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="广告标题">
          <el-input
            v-model="queryParams.adTitle"
            placeholder="请输入广告标题"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 180px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="scheduleList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="排期ID" width="80" />
        <el-table-column prop="advertisementTitle" label="广告标题" 
          show-overflow-tooltip />
        <el-table-column prop="deviceName" label="设备名称" 
          show-overflow-tooltip />
        <el-table-column label="投放时间" width="300">
          <template #default="scope">
            {{ formatTime(scope.row.startTime) }} 至 {{ formatTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="时间段" width="180">
          <template #default="scope">
            <div v-if="scope.row.timeSlots && scope.row.timeSlots.length > 0">
              <div v-for="(slot, index) in scope.row.timeSlots" :key="index" class="time-slot-item">
                {{ slot.startTime }} - {{ slot.endTime }}
              </div>
            </div>
            <span v-else>全天</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] || scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="效果数据" width="180">
          <template #default="scope">
            <div>展示: {{ scope.row.impressions || 0 }}</div>
            <div>点击: {{ scope.row.clicks || 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              v-if="canCancel(scope.row)"
              type="danger"
              link
              @click="handleCancel(scope.row)"
            >
              取消排期
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        class="pagination"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getAdvertiserSchedules, cancelSchedule } from '@/api/schedule'
import dayjs from 'dayjs'

const router = useRouter()
const loading = ref(false)
const scheduleList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  adTitle: '',
  deviceName: '',
  status: ''
})

// 状态选项
const statusOptions = [
  { label: '待执行', value: 'PENDING' },
  { label: '执行中', value: 'RUNNING' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' }
]

// 状态映射
const statusMap = {
  'PENDING': '待执行',
  'RUNNING': '执行中',
  'COMPLETED': '已完成',
  'CANCELLED': '已取消'
}

// 获取排期列表
const getScheduleList = async () => {
  try {
    loading.value = true
    const res = await getAdvertiserSchedules(queryParams)
    console.log('res.data:', res.data)
    
    if (res.data.code === 200) {
      scheduleList.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error(res.data.message || '获取排期列表失败')
    }
  } catch (error) {
    console.error('获取排期列表失败:', error)
    ElMessage.error('获取排期列表失败')
  } finally {
    loading.value = false
  }
}

// 判断是否可以取消排期
const canCancel = (row) => {
  return ['PENDING', 'RUNNING'].includes(row.status)
}

// 处理取消排期
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消排期 #${row.id} (${row.advertisementTitle} - ${row.deviceName}) 吗？`,
      '取消排期',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '返回',
        type: 'warning'
      }
    )
    
    const res = await cancelSchedule(row.id)
    
    if (res.data.code === 200) {
      ElMessage.success('排期已成功取消')
      getScheduleList() // 刷新列表
    } else {
      ElMessage.error(res.data.message || '取消排期失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消排期失败:', error)
      ElMessage.error('取消排期失败')
    }
  }
}

// 查看详情
const handleViewDetails = (row) => {
  router.push(`/advertiser/details/${row.id}`)
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getScheduleList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.adTitle = ''
  queryParams.deviceName = ''
  queryParams.status = ''
  handleSearch()
}

// 页码变化
const handlePageChange = (newPage) => {
  queryParams.pageNum = newPage
  getScheduleList()
}

// 每页条数变化
const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize
  queryParams.pageNum = 1
  getScheduleList()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'info',
    'RUNNING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 时间格式化
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '--'
}

onMounted(() => {
  getScheduleList()
})
</script>

<style scoped>
.schedule-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}
.page-header h2{
  font-size: 24px;
  font-weight: 500;
}
.search-form {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.time-slot-item {
  margin-bottom: 5px;
}

.time-slot-item:last-child {
  margin-bottom: 0;
}
</style>